document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('textInput');
    const generateBtn = document.getElementById('generateBtn');
    const qrCodeContainer = document.getElementById('qrcode');
    const charCount = document.getElementById('charCount');
    const downloadBtn = document.getElementById('downloadBtn');
    const clearBtn = document.getElementById('clearBtn');
    
    let qrCodeInstance = null;
    
    // 更新字符计数
    function updateCharCount() {
        const text = textInput.value;
        const count = text.length;
        charCount.textContent = `字符数: ${count}`;
        
        // 根据字符数量改变颜色
        if (count > 1000) {
            charCount.style.color = '#ff4444';
        } else if (count > 500) {
            charCount.style.color = '#ff8800';
        } else {
            charCount.style.color = '#666';
        }
    }
    
    // 生成二维码
    function generateQRCode() {
        const text = textInput.value.trim();
        
        if (!text) {
            alert('请输入要生成二维码的内容');
            return;
        }
        
        // 清除之前的二维码
        qrCodeContainer.innerHTML = '';
        
        try {
            // 创建新的二维码实例
            qrCodeInstance = new QRCode(qrCodeContainer, {
                text: text,
                width: 256,
                height: 256,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            });
            
            // 显示下载按钮
            downloadBtn.style.display = 'inline-block';
            
            console.log('二维码生成成功');
        } catch (error) {
            console.error('生成二维码时出错:', error);
            alert('生成二维码失败，请检查输入内容');
        }
    }
    
    // 下载二维码
    function downloadQRCode() {
        if (!qrCodeInstance) {
            alert('请先生成二维码');
            return;
        }
        
        try {
            // 查找二维码表格
            const qrTable = qrCodeContainer.querySelector('table');
            if (!qrTable) {
                alert('未找到二维码，请重新生成');
                return;
            }
            
            // 创建canvas来绘制二维码
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const size = 256;
            canvas.width = size;
            canvas.height = size;
            
            // 获取二维码的行和列
            const rows = qrTable.querySelectorAll('tr');
            const moduleCount = rows.length;
            const moduleSize = size / moduleCount;
            
            // 绘制二维码到canvas
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, size, size);
            
            ctx.fillStyle = '#000000';
            for (let row = 0; row < moduleCount; row++) {
                const cells = rows[row].querySelectorAll('td');
                for (let col = 0; col < cells.length; col++) {
                    const cell = cells[col];
                    const bgColor = window.getComputedStyle(cell).backgroundColor;
                    // 检查是否为黑色模块
                    if (bgColor === 'rgb(0, 0, 0)' || bgColor === '#000000') {
                        ctx.fillRect(
                            col * moduleSize,
                            row * moduleSize,
                            moduleSize,
                            moduleSize
                        );
                    }
                }
            }
            
            // 下载图片
            canvas.toBlob(function(blob) {
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'qrcode.png';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            });
            
        } catch (error) {
            console.error('下载二维码时出错:', error);
            alert('下载失败，请重试');
        }
    }
    
    // 清除二维码
    function clearQRCode() {
        textInput.value = '';
        qrCodeContainer.innerHTML = '';
        downloadBtn.style.display = 'none';
        qrCodeInstance = null;
        updateCharCount();
    }
    
    // 事件监听器
    textInput.addEventListener('input', updateCharCount);
    textInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            generateQRCode();
        }
    });
    
    generateBtn.addEventListener('click', generateQRCode);
    downloadBtn.addEventListener('click', downloadQRCode);
    clearBtn.addEventListener('click', clearQRCode);
    
    // 初始化字符计数
    updateCharCount();
    
    // 自动聚焦到输入框
    textInput.focus();
});

// 错误处理
window.addEventListener('error', function(e) {
    console.error('页面错误:', e.error);
});

// 检查QRCode库是否加载
if (typeof QRCode === 'undefined') {
    console.error('QRCode库未加载');
    document.addEventListener('DOMContentLoaded', function() {
        const container = document.getElementById('qrcode');
        if (container) {
            container.innerHTML = '<p style="color: red; text-align: center;">二维码库加载失败，请刷新页面重试</p>';
        }
    });
}